package com.htrq.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.htrq.entity.TResource;
import com.htrq.entity.User;

/**
 * 过滤权限用的过滤器
 */
public class LoginFilter implements Filter {
	private static List<TResource> rights;

	public static List<TResource> getRights() {
		return rights;
	}
	/**
	 * Default constructor.
	 */
	public LoginFilter() {
	}
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request2, ServletResponse response2, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) request2;
		HttpServletResponse response = (HttpServletResponse) response2;
		String uri = request.getRequestURI();
		System.out.println("--时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"----当前请求路径-----" + uri);
		// 判断是否是登录操作
		if (uri.startsWith("/htrqms/syslogin.do") || uri.startsWith("/htrqms/jsp/sys/getRight.do")) {
			chain.doFilter(request, response);
		} else {// 执行过滤
				// 检查用户是否登录
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print("<script language=\"javascript\">window.top.location.href='/htrqms/login.jsp';</script>");
			} else {
				/**
				 * 从session取权限出来，用当前的请求跟取出来权限对比 有则说明是合法请求，通过 无则说明是非法请求，不通过
				 */
				List<TResource> rights = (List<TResource>) request.getSession().getAttribute("right");
				String currenturl = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
				Map<String, String> map = new HashMap<String, String>();
				for (TResource tr : rights) {
					String href = tr.getHrefTarget();
					map.put(href, tr.getText());
				}
				;
				if (rights != null) {
					if (map.containsKey(currenturl)) {
						chain.doFilter(request, response);
					} else {
						throw new RuntimeException("无权操作");
					}
				}
			}
		}
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}
}
